﻿using System;
using System.Reflection;
using System.ComponentModel;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Flagwind.Plugins;
using Flagwind.Plugins.Builders;

namespace Flagwind.ComponentModel.Plugins.Builders
{
	public class ComponentBuilder : Flagwind.Plugins.Builders.BuilderBase
	{
		#region 重写方法

		protected override void OnBuilt(BuilderContext context)
		{
			IContainer container = null;
			IComponent component = context.Result as IComponent;

			if(component == null)
			{
				return;
			}

			container = context.Owner as IContainer;

			if(container == null)
			{
				var workbench = context.Owner as IWorkbench;

				if(workbench == null)
				{
					container = this.GetContainer(context.Owner);
				}
				else
				{
					container = workbench.Window as IContainer;

					if(container == null)
					{
						container = this.GetContainer(workbench.Window);
					}
				}
			}

			if(container != null)
			{
				container.Add(component, context.Builtin.Name);
			}
		}

		#endregion

		#region 私有方法

		private IContainer GetContainer(object target)
		{
			if(target == null)
			{
				return null;
			}

			var memberInfo = target.GetType().FindMembers((MemberTypes.Field | MemberTypes.Property), (BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.GetField | BindingFlags.GetProperty), (member, criteria) =>
			{
				if(member.MemberType == MemberTypes.Field)
				{
					return typeof(IContainer).IsAssignableFrom(((FieldInfo)member).FieldType);
				}

				if(member.MemberType == MemberTypes.Property)
				{
					return typeof(IContainer).IsAssignableFrom(((PropertyInfo)member).PropertyType);
				}

				return false;
			}, null).FirstOrDefault();

			if(memberInfo.MemberType == MemberTypes.Field)
			{
				return ((FieldInfo)memberInfo).GetValue(target) as IContainer;
			}

			if(memberInfo.MemberType == MemberTypes.Property)
			{
				return ((PropertyInfo)memberInfo).GetValue(target, null) as IContainer;
			}

			return null;
		}

		#endregion
	}
}